import base64  # 导入base64模块，用于Base64编码和解码
import hashlib  # 导入hashlib模块，用于计算SHA256哈希值
import hmac  # 导入hmac模块，用于生成HMAC哈希值
import json  # 导入json模块，用于处理JSON数据
import os
from datetime import datetime  # 从datetime模块中导入datetime类，用于获取当前时间
from time import mktime  # 从time模块中导入mktime函数，用于将时间元组转换为时间戳
from urllib.parse import urlencode  # 从urllib.parse模块中导入urlencode函数，用于URL编码
from wsgiref.handlers import format_date_time  # 从wsgiref.handlers模块中导入format_date_time函数，用于格式化日期时间

import requests  # 导入requests模块，用于发送HTTP请求

APPId = "1572eec0"  # 控制台获取的APPId
APISecret = "OTEyZTBkMDdlN2ZhZmZiNDkzYzZiNmQ2"  # 控制台获取的APISecret
APIKey = "bb7d91990af07d048a0261acac47e4be"  # 控制台获取的APIKey

# 打开图像文件
input_image_path = r'D:\Code\python\universal_character_recognition_python_demo\big.png'
output_image_path = r'grayscale_big.jpg'

from PIL import Image

# 使用Pillow打开图像
with Image.open(input_image_path) as img:
    # 将图像转换为RGB模式
    rgb_img = img.convert('RGB')
    # 保存图像并指定优化参数
    rgb_img.save(output_image_path, optimize=True)

print(f"图像已成功压缩并保存")


# 读取图像文件并转换为字节流
with open(output_image_path, "rb") as f:
    imageBytes = f.read()
os.remove(output_image_path)
# 自定义异常类，用于处理组装头部时的错误
class AssembleHeaderException(Exception):
    def __init__(self, msg):
        self.message = msg

# URL类，用于存储解析后的URL信息
class Url:
    def __init__(self, host, path, schema):
        self.host = host
        self.path = path
        self.schema = schema
        pass

# 计算SHA256并编码为Base64
def sha256base64(data):
    sha256 = hashlib.sha256()  # 创建SHA256哈希对象
    sha256.update(data)  # 更新哈希对象的数据
    digest = base64.b64encode(sha256.digest()).decode(encoding='utf-8')  # 计算哈希值并进行Base64编码
    print("打印哈希值的大小（字节数）",digest.__sizeof__())  # 打印哈希值的大小（字节数）
    return digest  # 返回Base64编码的哈希值

# 解析URL并返回Url对象
def parse_url(requset_url):
    stidx = requset_url.index("://")  # 查找协议分隔符的位置
    host = requset_url[stidx + 3:]  # 提取主机部分
    schema = requset_url[:stidx + 3]  # 提取协议部分
    edidx = host.index("/")  # 查找路径分隔符的位置
    if edidx <= 0:
        raise AssembleHeaderException("invalid request url:" + requset_url)  # 如果路径分隔符不存在，抛出异常
    path = host[edidx:]  # 提取路径部分
    host = host[:edidx]  # 提取主机部分
    u = Url(host, path, schema)  # 创建Url对象
    return u  # 返回Url对象

# 构建WebSocket认证请求URL
def assemble_ws_auth_url(requset_url, method="POST", api_key="", api_secret=""):
    u = parse_url(requset_url)  # 解析请求URL
    host = u.host  # 获取主机部分
    path = u.path  # 获取路径部分
    now = datetime.now()  # 获取当前时间
    date = format_date_time(mktime(now.timetuple()))  # 格式化当前时间为GMT格式的字符串
    print(date)  # 打印日期时间字符串
    # date = "Thu, 12 Dec 2019 01:57:27 GMT"
    signature_origin = "host: {}\ndate: {}\n{} {} HTTP/1.1".format(host, date, method, path)  # 构建签名原始字符串
    # print(signature_origin)  # 打印签名原始字符串
    print("打印签名原始字符串")
    signature_sha = hmac.new(api_secret.encode('utf-8'), signature_origin.encode('utf-8'),
                             digestmod=hashlib.sha256).digest()  # 使用HMAC-SHA256算法计算签名哈希值
    signature_sha = base64.b64encode(signature_sha).decode(encoding='utf-8')  # 对签名哈希值进行Base64编码
    authorization_origin = "api_key=\"%s\", algorithm=\"%s\", headers=\"%s\", signature=\"%s\"" % (
        api_key, "hmac-sha256", "host date request-line", signature_sha)  # 构建授权原始字符串
    authorization = base64.b64encode(authorization_origin.encode('utf-8')).decode(encoding='utf-8')  # 对授权原始字符串进行Base64编码
    # print(authorization_origin)  # 打印授权原始字符串
    print("打印授权原始字符串")
    values = {
        "host": host,  # 添加主机部分到字典
        "date": date,  # 添加日期时间字符串到字典
        "authorization": authorization  # 添加授权字符串到字典
    }

    return requset_url + "?" + urlencode(values)  # 返回带有查询参数的完整URL

# API请求的URL
url = 'https://api.xf-yun.com/v1/private/sf8e6aca1'

# 请求体，包含header、parameter和payload字段
body = {
    "header": {
        "app_id": APPId,  # 设置应用ID
        "status": 3  # 设置状态码
    },
    "parameter": {
        "sf8e6aca1": {
            "category": "ch_en_public_cloud",  # 设置分类
            "result": {
                "encoding": "utf8",  # 设置编码格式
                "compress": "raw",  # 设置压缩方式
                "format": "json"  # 设置格式
            }
        }
    },
    "payload": {
        "sf8e6aca1_data_1": {
            "encoding": "jpg",  # 设置编码格式
            "image": str(base64.b64encode(imageBytes), 'UTF-8'),  # 将图像字节流进行Base64编码并转换为字符串
            "status": 3  # 设置状态码
        }
    }
}

# 构建带认证信息的请求URL
request_url = assemble_ws_auth_url(url, "POST", APIKey, APISecret)

# 设置请求头信息
headers = {'content-type': "application/json", 'host': 'api.xf-yun.com', 'app_id': APPId}
print(request_url)  # 打印请求URL
response = requests.post(request_url, data=json.dumps(body), headers=headers)  # 发送POST请求
print(response)  # 打印响应对象
# print(response.content)  # 打印响应内容
#
# print("resp=>" + response.content.decode())  # 打印响应内容的解码结果
tempResult = json.loads(response.content.decode())  # 将响应内容解析为JSON对象

# 解码Base64编码的文本字段并去除多余的空白字符
finalResult = base64.b64decode(tempResult['payload']['result']['text']).decode()
finalResult = finalResult.replace(" ", "").replace("\n", "").replace("\t", "").strip()
# print("text字段Base64解码后=>" + finalResult)  # 打印最终结果
print("结果打印")
# data   page   lines   word    content = 战斗   coord
keywords = '登龙见四野'

finalResult = json.loads(finalResult)
for pages in finalResult['pages']:
    for lines in pages['lines']:
        if 'words' in lines:
            for words in lines['words']:
                if words['content'] == keywords:
                    location = words['coord']
                    print(location)
